import Cookies from "js-cookie";
import qs from "qs";
export default {
  data() {
    /* eslint-disable */
    return {
      // 设置属性
      mixinViewModuleOptions: {
        createdIsNeed: true, // 此页面是否在创建时，调用查询数据列表接口？
        activatedIsNeed: false, // 此页面是否在激活（进入）时，调用查询数据列表接口？
        getURL: "", // 数据列表接口，API地址
        isPage: false, // 数据列表接口，是否需要分页？
        deleteURL: "", // 删除接口，API地址
        deleteIsBatch: false, // 删除接口，是否需要批量？
        deleteIsBatchKey: "id", // 删除接口，批量状态下由那个key进行标记操作？比如：pid，uid...
        exportURL: "", // 导出接口，API地址
        type: "get", // 请求方式
      },
      // 默认属性
      dataForm: {}, // 查询条件
      dataList: [], // 数据列表
      order: "", // 排序，asc／desc
      orderField: "", // 排序，字段
      page: 1, // 当前页码
      limit: 10, // 每页数
      pageSize: 10,
      total: 0, // 总条数
      dataListLoading: false, // 数据列表，loading状态
      dataListSelections: [], // 数据列表，多选项
      addOrUpdateVisible: false, // 新增／更新，弹窗visible状态
      deleteType: "post", //删除请求方式
    };
    /* eslint-enable */
  },
  created() {
    if (this.mixinViewModuleOptions.createdIsNeed) {
      this.query();
    }
  },
  activated() {
    if (this.mixinViewModuleOptions.activatedIsNeed) {
      this.query();
    }
  },
  methods: {
    // 获取数据列表
    query() {
      this.dataListLoading = true;
      if (!this.mixinViewModuleOptions.getURL) {
        return console.error("未配置mixinViewModuleOptions.getURL");
      }
      let form = {
        params: {
          ...this.dataForm,
          order: this.order,
          orderField: this.orderField,
          page: this.mixinViewModuleOptions.isPage ? this.page : null,
          limit: this.mixinViewModuleOptions.isPage ? this.limit : null,
          pageSize: this.mixinViewModuleOptions.isPage ? this.pageSize : null,
        },
      };
      if (this.mixinViewModuleOptions.type.toLocaleLowerCase() !== "get") {
        form = form.params || {};
      } else {
        form.params = form.params || {};
        form.params._v = Math.random();
      }
      return this.$http[this.mixinViewModuleOptions.type](
        this.mixinViewModuleOptions.getURL,
        {
          v: "mapList",
        }
      )
        .then((res) => {
          this.dataListLoading = false;
          // if (res.code != 200) {
          //   this.dataList = []
          //   this.total = 0;
          //   return this.$message.error(res.message)
          // }
          console.log("this is get Device list=========<", res);
          let r = res.data.data;
          let tmp = this.fetchComplete(false, r, res);

          this.dataList = r || tmp;
          // this.total = this.mixinViewModuleOptions.isPage ? res.data.total : 0;
        })
        .catch((err) => {
          this.dataListLoading = false;
        });
    },
    fetchComplete(err, data = [], res) {
      return data;
    },
    // 多选
    dataListSelectionChangeHandle(val) {
      this.dataListSelections = val;
    },
    // 排序
    dataListSortChangeHandle(data) {
      if (!data.order || !data.prop) {
        this.order = "";
        this.orderField = "";
        return false;
      }
      this.order = data.order.replace(/ending$/, "");
      this.orderField = data.prop.replace(/([A-Z])/g, "_$1").toLowerCase();
      this.query();
    },
    // 分页, 每页条数
    pageSizeChangeHandle(val) {
      this.page = 1;
      this.limit = val;
      // console.log(val);
      this.query();
    },
    // 分页, 每页条数
    pagesSizesChangeHandle(val) {
      this.page = 1;
      this.pageSize = val;
      // console.log('pagesize',val);
      this.query();
    },
    pagesCurrentChangeHandle(val) {
      this.page = val;
      this.query();
    },
    // 分页, 当前页
    pageCurrentChangeHandle(val) {
      this.page = val;
      this.query();
    },
    getDataList: function () {
      this.page = 1;
      this.query();
    },
    // 新增 / 修改
    addOrUpdateHandle(id, obj) {
      this.addOrUpdateVisible = true;
      // this.$refs.addOrUpdate.dataForm.id = id
      this.$nextTick(() => {
        this.$refs.addOrUpdate.dataForm.id = id;
        this.$refs.addOrUpdate.init();
      });
    },
    // 关闭当前窗口
    closeCurrentTab(data) {
      var tabName = this.$store.state.contentTabsActiveName;
      this.$store.state.contentTabs = this.$store.state.contentTabs.filter(
        (item) => item.name !== tabName
      );
      if (this.$store.state.contentTabs.length <= 0) {
        this.$store.state.sidebarMenuActiveName =
          this.$store.state.contentTabsActiveName = "home";
        return false;
      }
      if (tabName === this.$store.state.contentTabsActiveName) {
        this.$router.push({
          name: this.$store.state.contentTabs[
            this.$store.state.contentTabs.length - 1
          ].name,
        });
      }
    },
    // 删除
    deleteHandle(id) {
      if (
        this.mixinViewModuleOptions.deleteIsBatch &&
        !id &&
        this.dataListSelections.length <= 0
      ) {
        return this.$message({
          message: "请选择删除项",
          type: "warning",
          duration: 500,
        });
      }
      this.$confirm("是否确认删除？", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let data = {};
          if (id) {
            data["id"] = id;
          } else if (this.mixinViewModuleOptions.deleteIsBatch) {
            let arr = this.dataListSelections.map(
              (item) => item[this.mixinViewModuleOptions.deleteIsBatchKey]
            );
            console.log(
              arr,
              "  this.dataListSelections",
              this.dataListSelections
            );
            data["id"] = arr;
          }
          if (!data.id) return this.$message.error("请传入要删除的项!");
          if (
            this.deleteType &&
            this.deleteType.toLocaleLowerCase() === "delete"
          ) {
            data = {
              data,
            };
          }
          this.$http[this.deleteType](
            `${this.mixinViewModuleOptions.deleteURL}${
              this.mixinViewModuleOptions.deleteIsBatch ? "" : ""
            }`,
            data
          )
            .then((res) => {
              if (res.code !== 200) {
                return this.$message.error(res.message);
              }
              this.fetchComplete(false, res.data, res);
              //  debugger
              this.$message({
                message: "删除成功",
                type: "success",
                duration: 500,
                onClose: () => {
                  this.query();
                },
              });
            })
            .catch(() => {});
        })
        .catch(() => {});
    },
    // 导出
    exportHandle() {
      var params = qs.stringify({
        token: Cookies.get("token"),
        ...this.dataForm,
      });
      window.location.href = `${window.SITE_CONFIG["apiURL"]}${this.mixinViewModuleOptions.exportURL}?${params}`;
    },
  },
};
